package main.java.com.web;

import main.java.com.entity.Dish;
import main.java.com.service.DishService;
import main.java.com.service.impl.DishServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//查询所有以及分页
@WebServlet("/DishListServlet")
public class DishServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        // 获取请求参数中的关键字
        String keyword = request.getParameter("keyword");
        // 获取请求参数中的状态字符串
        String statusStr = request.getParameter("status");
        // 初始化状态为null
        Integer status = null;
        // 如果状态字符串不为空，则解析为整数
        if (statusStr!= null &&!statusStr.isEmpty()) {
            status = Integer.parseInt(statusStr);
        }

        // 默认页码为1
        int page = 1;
        // 获取请求参数中的页码字符串
        String pageStr = request.getParameter("page");
        // 如果页码字符串不为空，则解析为整数
        if (pageStr!= null &&!pageStr.isEmpty()) {
            page = Integer.parseInt(pageStr);
        }
        // 定义每页显示的数量
        int pageSize = 5; // 每页显示数量

        // 创建DishService实例
        DishService dishService = new DishServiceImpl();
        // 调用服务获取菜品列表
        List<Dish> dishes = dishService.getAllDishes(page, pageSize, keyword, status);
        // 调用服务获取菜品总数
        int totalCount = dishService.getDishCount(keyword, status);
        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        // 打印调试信息
        System.out.println(dishes.size());
        System.out.println(page);
        System.out.println(pageSize);

        // 设置请求属性，用于展示在页面上
        request.setAttribute("dishes", dishes);
        request.setAttribute("keyword", keyword);
        request.setAttribute("status", status);
        request.setAttribute("page", page);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalPages", totalPages);

        // 转发请求到/dishList.jsp
        request.getRequestDispatcher("/backend/dishList.jsp").forward(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}


